<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useSettingsStore } from './stores/settingsStore'
import { 
  Fold,
  Expand,
  HomeFilled,
  Reading,
  TakeawayBox,
  Back,
  Brush,
  Bell,
  Setting,
  ArrowDown,
  Close,
  InfoFilled,
  Tools,
  User
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const settingsStore = useSettingsStore()
const isCollapse = ref(localStorage.getItem('menuCollapse') === 'true')
const activeMenu = computed(() => route.path)
const breadcrumbs = ref([])
const currentLanguage = ref(settingsStore.language)
const currentTheme = ref(settingsStore.theme)
const messageCount = ref(0)

// 菜单标题映射
const menuTitles = {
  '/': '首页',
  '/books': '图书管理',
  '/borrow': '借阅管理',
  '/return': '归还管理',
  '/version': '版本信息',
  '/config': '系统配置',
  '/about': '关于我们'
}

// 更新面包屑
const updateBreadcrumb = () => {
  const path = route.path;
  const title = menuTitles[path];

  // 忽略不在菜单映射中的路径
  if (!title) return;

  // 确保首页在第一位
  if (breadcrumbs.value.length === 0 || breadcrumbs.value[0].path !== '/') {
    breadcrumbs.value.unshift({ path: '/', title: '首页' });
    // 去重
    breadcrumbs.value = breadcrumbs.value.filter((item, index, self) =>
      index === self.findIndex((t) => (t.path === item.path))
    );
  }

  // 如果是新路径且不是首页，添加到面包屑
  const existingIndex = breadcrumbs.value.findIndex(item => item.path === path);
  if (existingIndex === -1 && path !== '/') {
    breadcrumbs.value.push({ path, title });
  }

  localStorage.setItem('breadcrumbs', JSON.stringify(breadcrumbs.value));
};

// 移除面包屑
const removeBreadcrumb = (index) => {
  // 不允许移除首页
  if (index === 0) return;
  
  const removedPath = breadcrumbs.value[index].path;
  
  // 只移除当前点击的面包屑
  breadcrumbs.value.splice(index, 1);
  
  localStorage.setItem('breadcrumbs', JSON.stringify(breadcrumbs.value));
  
  // 如果移除的是当前页面，跳转到最后一个面包屑
  if (route.path === removedPath) {
    const lastBreadcrumb = breadcrumbs.value[breadcrumbs.value.length - 1];
    if (lastBreadcrumb) {
      router.push(lastBreadcrumb.path);
    } else {
      router.push('/');
    }
  }
};

// 监听路由变化，更新面包屑
watch(route, () => {
  updateBreadcrumb()
}, { immediate: true })

onMounted(() => {
  // 初始化主题
  settingsStore.initTheme()
  
  // 从localStorage获取菜单折叠状态
  isCollapse.value = localStorage.getItem('menuCollapse') === 'true'
  
  // 初始化面包屑
  const savedBreadcrumbs = localStorage.getItem('breadcrumbs')
  if (savedBreadcrumbs) {
    try {
      const parsed = JSON.parse(savedBreadcrumbs);
      if (Array.isArray(parsed)) {
        breadcrumbs.value = parsed;
        // 确保加载后也符合规则 (特别是首页第一条)
        updateBreadcrumb(); 
      } else {
        console.warn('Invalid breadcrumbs data in localStorage, initializing fresh.');
        breadcrumbs.value = [];
        updateBreadcrumb();
      }
    } catch (e) {
      console.error('Error parsing breadcrumbs from localStorage', e);
      breadcrumbs.value = [];
      updateBreadcrumb();
    }
  } else {
    // 没有保存的数据，基于当前路由初始化
    breadcrumbs.value = [];
    updateBreadcrumb();
  }
})

const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
  localStorage.setItem('menuCollapse', isCollapse.value)
}

const handleLanguageChange = (lang) => {
  currentLanguage.value = lang
  settingsStore.language = lang
}

const handleThemeChange = (theme) => {
  currentTheme.value = theme
  settingsStore.theme = theme
}
</script>

<template>
  <el-container class="app-container">
    <el-aside :width="isCollapse ? '64px' : '200px'">
      <div class="logo">
        <img src="./assets/logo.png" alt="Logo" />
        <span v-show="!isCollapse">图书管理系统</span>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical"
        :collapse="isCollapse"
        :router="true"
      >
        <!-- 主要功能菜单 -->
        <el-menu-item index="/">
          <el-icon><HomeFilled /></el-icon>
          <template #title>首页</template>
        </el-menu-item>
        <el-menu-item index="/books">
          <el-icon><Reading /></el-icon>
          <template #title>图书管理</template>
        </el-menu-item>
        <el-menu-item index="/borrow">
          <el-icon><TakeawayBox /></el-icon>
          <template #title>借阅管理</template>
        </el-menu-item>
        <el-menu-item index="/return">
          <el-icon><Back /></el-icon>
          <template #title>归还管理</template>
        </el-menu-item>
        
        <!-- 设置菜单，加一个分隔条 -->
        <div class="menu-divider"></div>
        
        <!-- 设置菜单 -->
        <el-sub-menu index="settings">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </template>
          
          <el-menu-item index="/version">
            <el-icon><InfoFilled /></el-icon>
            <span>版本信息</span>
          </el-menu-item>
          
          <el-menu-item index="/config">
            <el-icon><Tools /></el-icon>
            <span>系统配置</span>
          </el-menu-item>
          
          <el-menu-item index="/about">
            <el-icon><User /></el-icon>
            <span>关于我们</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    
    <el-container>
      <el-header>
        <div class="header-left">
          <el-button
            type="text"
            @click="toggleCollapse"
          >
            <el-icon><Fold v-if="!isCollapse" /><Expand v-else /></el-icon>
          </el-button>
        </div>
        
        <div class="header-right">
          <el-dropdown @command="handleLanguageChange">
            <span class="header-button">
              <el-icon><Setting /></el-icon>
              {{ currentLanguage === 'zh' ? '中文' : 'English' }}
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="zh">中文</el-dropdown-item>
                <el-dropdown-item command="en">English</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <el-dropdown @command="handleThemeChange">
            <span class="header-button">
              <el-icon><Brush /></el-icon>
              {{ currentTheme === 'default' ? '默认主题' : 
                 currentTheme === 'dark' ? '暗黑主题' :
                 currentTheme === 'blue' ? '蓝色主题' : '绿色主题' }}
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="default">默认主题</el-dropdown-item>
                <el-dropdown-item command="dark">暗黑主题</el-dropdown-item>
                <el-dropdown-item command="blue">蓝色主题</el-dropdown-item>
                <el-dropdown-item command="green">绿色主题</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <el-dropdown>
            <span class="header-button">
              <el-icon><Bell /></el-icon>
              <el-badge :value="messageCount" :max="99" class="message-badge" />
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>暂无消息</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- 用户信息 -->
          <el-dropdown>
            <span class="header-button">
              管理员
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>个人信息</el-dropdown-item>
                <el-dropdown-item>修改密码</el-dropdown-item>
                <el-dropdown-item divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <div class="breadcrumb-container">
        <el-breadcrumb separator=" ">
          <!-- 首页面包屑 -->
          <el-breadcrumb-item :to="{ path: '/' }">
            <div class="breadcrumb-home" :class="{ 'active': route.path === '/' }">
              <el-icon><HomeFilled /></el-icon>
              <span>首页</span>
            </div>
          </el-breadcrumb-item>
          
          <!-- 其他面包屑 -->
          <el-breadcrumb-item 
            v-for="(item, index) in breadcrumbs.slice(1)" 
            :key="index" 
            :to="item.path"
          >
            <div 
              class="breadcrumb-item-box" 
              :class="{ 'active': route.path === item.path }"
            >
              <span class="breadcrumb-text">{{ item.title }}</span>
              <el-icon 
                class="breadcrumb-close" 
                @click.stop="removeBreadcrumb(index + 1)"
              >
                <Close />
              </el-icon>
            </div>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <el-main>
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<style scoped>
.app-container {
  height: 100vh;
}

.el-aside {
  background-color: var(--el-menu-bg-color);
  transition: width 0.3s;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  background-color: var(--el-menu-bg-color);
}

.logo img {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

.logo span {
  font-size: 18px;
  font-weight: bold;
  color: var(--el-text-color-primary);
  white-space: nowrap;
}

.el-menu-vertical {
  border-right: none;
}

.el-header {
  background-color: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-button {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
}

.header-button:hover {
  background-color: var(--el-fill-color-light);
}

.message-badge {
  margin-left: 4px;
}

.breadcrumb-container {
  padding: 16px 20px;
  background-color: #fff;
  border-bottom: 1px solid var(--el-border-color-light);
}

.breadcrumb-home {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: var(--el-text-color-primary);
  margin-right: 12px;
  padding: 4px 12px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  transition: all 0.3s;
}

.breadcrumb-home.active {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.breadcrumb-item-box {
  display: flex;
  align-items: center;
  padding: 4px 12px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  transition: all 0.3s;
  margin-right: 12px;
}

.breadcrumb-item-box.active {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.breadcrumb-text {
  font-size: 14px;
}

.breadcrumb-close {
  margin-left: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  cursor: pointer;
}

.breadcrumb-close:hover {
  color: var(--el-color-primary);
}

/* 覆盖 Element Plus 的默认面包屑分隔符样式 */
:deep(.el-breadcrumb__separator) {
  display: none;
}

:deep(.el-breadcrumb__item) {
  display: flex;
  align-items: center;
}

.el-main {
  background-color: var(--el-bg-color-page);
  padding: 20px;
}

/* 添加菜单分隔线样式 */
.menu-divider {
  height: 1px;
  margin: 15px 0;
  background-color: var(--el-border-color-light);
  opacity: 0.5;
}

/* 当菜单折叠时调整分隔线样式 */
.el-menu--collapse .menu-divider {
  margin: 15px auto;
  width: 60%;
}
</style>

<style>
/* 添加全局样式变量 */
:root {
  --el-color-primary: #409EFF;
  --el-bg-color: #f5f7fa;
  --el-text-color-primary: #303133;
}
</style>
